package com.kehongborui.fliggy.service.impl;

import com.kehongborui.fliggy.entity.User;
import com.kehongborui.fliggy.enums.SysConfig;
import com.kehongborui.fliggy.exception.FliggyException;
import com.kehongborui.fliggy.mapper.UserMapper;
import com.kehongborui.fliggy.model.LoginUser;
import com.kehongborui.fliggy.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.util.Date;

import static com.kehongborui.fliggy.enums.ExceptionMessage.*;
import static org.springframework.util.ObjectUtils.isEmpty;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-08-29
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(LoginUser user) {
        // 判断用户名或者电话号码或者email是否为空
        // 前端只会传用户名或者电话号码或者email参数中的一个值过来
        if (isEmpty(user.getUsername()) && isEmpty(user.getTel()) && isEmpty(user.getEmail())) {
            throw new FliggyException(String.format(USER_INFO_IS_NULL.getDesc()));
        }

        User select = userMapper.selectByTelOrUsernameOrEmail(user.getTel(), user.getEmail(), user.getUsername());
        // 用户为空
        if (select == null) {
            throw new FliggyException(String.format(USER_INFO_ERROR.getDesc(), user.getTel()));
        }

        // 判断用户是否激活
        if (!select.getDisabled()) {
            throw new FliggyException(USER_NOT_ENABLED.getDesc());
        }

        // 判断用户是否被锁定，如果锁定且在锁定的时间内，抛出异常，反之同行或者解锁
        if (select.getAccountLocked() && select.getLastLockedTime() != null && (System.currentTimeMillis() - select.getLastLockedTime().getTime()) > SysConfig.LOCK_TIME) {
            select.setAccountLocked(false);
            select.setAttempts(0);
        }

        if (select.getAccountLocked()) {
            throw new FliggyException(USER_IS_LOCKED.getDesc());
        }

        // 更改用户登录时间，访问ip,
        select.setLastVisit(new Date());
        select.setLastIp(user.getLastIp());

        // 用户不存在 以及用户密码校验
        if (!select.getPassword().equals(user.getPassword())) {
            // 更改用户密码尝试次数
            select.setAttempts(select.getAttempts() + 1);
            // 密码尝试超过限制，禁用该账号
            if (select.getAttempts() == SysConfig.ALLOW_ATTEMPT) {
                select.setAccountLocked(true);
                select.setLastLockedTime(new Date());
            }

            userMapper.updateByPrimaryKeySelective(select);
            throw new FliggyException(String.format(USER_INFO_ERROR.getDesc(), user.getTel()));
        }

        // 加等级
        select.setAttempts(0);
        select.setLevel(select.getLevel() + 1);
        userMapper.updateByPrimaryKeySelective(select);
        return select;
    }
}
